package com.bird.user.application

import cn.dev33.satoken.stp.StpUtil
import com.bird.component.lang.common.exception.ServiceException
import com.bird.component.lang.util.isnull
import com.bird.user.application.converter.toMeResponse
import com.bird.user.application.converter.toUserInfoApiRes
import org.springframework.stereotype.Service
import com.bird.component.security.common.util.userId
import com.bird.user.application.pl.MeResponse
import com.bird.user.application.pl.UserInfoResponse
import com.bird.user.application.pl.UserStatusInfo

@Service
class UserQueryService(val userAppQueryRepository: UserAppQueryRepository) {
    /**
     * 获取用户信息
     */
    fun oneUser(userId: Long): UserInfoResponse? {
        return userAppQueryRepository.oneUser(userId)?.toUserInfoApiRes()
    }

    /**
     * 获取用户信息
     */
    fun oneUser(username:String, password:String): UserInfoResponse? {
        val userEntity = userAppQueryRepository.oneUserByUsername(username)
        return userEntity?.takeIf { it.checkPassword(password) }?.toUserInfoApiRes()
    }
    /**
     * 获取我的用户信息
     */
    fun me(): MeResponse {
        val userId = userId()
        if (userId.isnull()) {
            throw ServiceException(UserStatusInfo.USER_NOT_LOGIN)
        }
        return (userAppQueryRepository.oneUser(userId!!) ?: throw ServiceException(UserStatusInfo.USER_NOT_EXIST))
            .toMeResponse(StpUtil.getPermissionList())
    }


}